﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using SIA.Configurators;

namespace SIA.HwAccess.PLCSiemens
{




    public class S7Int : S7Signal, IIntegerSignal
    {
        //Eventi
        public override event SignalEvent ValueChange;       

        //Dati
        private Int16 _value;
        public override object Value { get { return IntValue; } set { this.IntValue = (Int16)value; } }
        public int IntValue { get { return (int)_value; } set {

            //Richiesta scrittura Dati
            _connection.requestWriteData(_address, 0, BitConverter.GetBytes(value)[1]);
            _connection.requestWriteData(_address, 1, BitConverter.GetBytes(value)[0]);

            //Verifica presenza eventi
            if (_value != (Int16)value)
            {
                _value = (Int16)value;               
               if (this.ValueChange != null) this.ValueChange(this);
            }
        } }

        /// <summary>Costruttore generico</summary>
        /// <param name="signalProperty"></param>
        /// <param name="connection"></param>
        public S7Int(IDictionaryProperty signalProperty, IHwConnection connection)
            : base(signalProperty, connection)
        {
            _connection.DataArrived += new ConnectionDataEvent(_connection_DataArrived);
        }

        /// <summary>Gestione evento arrivati nuovi dati</summary>
        /// <param name="conn"></param>
        /// <param name="data"></param>
        void _connection_DataArrived(IHwConnection conn, IRawData data)
        {
            //Verifica presenza della DataKey
            if (data.ContainsKey(_address.DataKey))
            {
                //Appoggio: valore precedente
                Int16 oldValue = _value;
                //Scrittura
                _value = BitConverter.ToInt16(new Byte[] { data[_address.DataKey][_address.StartByte], data[_address.DataKey][_address.StartByte + 1] }, 0);
                //Verifica presenza eventi
                if (oldValue != _value)
                    if (this.ValueChange != null) this.ValueChange(this);
            }
            else
                SIA.Messages.MessageManager.sendMessage(this, "Dati non presenti nella connessione", SIA.Messages.eMessageType.DEBUG);
        }

        
    }
}
